<?php
/**
 * 加密用户信息
 * @param array $data
 * @return string
 */
function user_encrypt($data = [])
{
    $data['iat'] = time();//token 生成时间
    $data['exp'] = $data['iat'] + 3600;//过期时间
    $secret_key = 'youhuitao_key';
    $secret_iv = 'youhuitao_iv';
    $encrypt_method = "AES-256-CBC";
    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    return base64_encode(openssl_encrypt(json_encode($data), $encrypt_method, $key, 0, $iv));
}

/**
 * 解密用户信息
 * @param string $string
 * @return mixed|object
 */
function user_decrypt($string = '')
{
    $secret_key = 'youhuitao_key';
    $secret_iv = 'youhuitao_iv';
    $encrypt_method = "AES-256-CBC";
    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    return json_decode(openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv));
}

/**
 * 获取客户端ip
 * @return string
 */
function getClientIp()
{
    if (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    } else {
        $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
    }

    return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
}